let PENDING = 'pending'
let FULFILLED = 'fulfilled'
let REJECTED = 'rejected'

class Expromise {
    //执行器也就是promise的回调函数传了两个参数
    //所以executor要接收两个参数，这两个参数是函数
    constructor(executor) {
        this.value = ''

        //promise对象代理的三个状态值 pending fulfilled rejected
        this.status = PENDING

        //立即执行器接收两个参数 这两个参数都是函数
        this.success_arr = []
        this.fail_arr = []

        let resolvefn = (value) => {
            this.status = FULFILLED
            this.value = value
            this.success_arr.map(item => {
                item(value)
            })
        }
        let rejectfn = (result) => {
            this.status = REJECTED
            this.value = result
            this.fail_arr.map(item => {
                item(result)
            })
        }
        executor(resolvefn,rejectfn)
    }
    //then返回一个promise对象
    then(res, rej) {
        return new Expromise((resolve, reject) => { 
            this.success_arr.push(() => {
                let x = res(this.value);
                resolve(x);
            });
            this.fail_arr.push(() => {
                let x = rej(this.value);
                reject(x);
            });
        })
    }
    catch(reject) { 
        return this.then(null, reject)
    }
}

let p1 = new Expromise((resolve, reject) => {
    setTimeout(() => { // 异步请求
        resolve("测试成功")
    //    reject("测试失败") 
    }, 0);
}).then((res) => {
    console.log("then1", res);
    return res;
}, err => {
    console.log('error',err);  
})
console.log(p1);




